// bingfa.js
let limitedFetchInstance = null;

const limitConcurrentRequests = (requestFn, maxConcurrent) => {
  console.log('调用');
  const queue = [];
  let activeCount = 0;

  const enqueue = () => {
    if (queue.length === 0 || activeCount >= maxConcurrent) {
      return Promise.resolve();
    }

    const { fn, resolve, reject } = queue.shift();

    activeCount++;
    fn()
      .then(resolve)
      .catch(reject)
      .finally(() => {
        console.log('处理完成');
        activeCount--;
        enqueue();
      });
  };

  return function (...args) {
    return new Promise((resolve, reject) => {
      queue.push({
        fn: () => requestFn(...args),
        resolve,
        reject
      });

      if (activeCount < maxConcurrent) {
        enqueue();
      }
    });
  };
};

// 单例模式确保 `limitConcurrentRequests` 只初始化一次
export const getLimitedFetch = (requestFn, maxConcurrent) => {
  if (!limitedFetchInstance) {
    limitedFetchInstance = limitConcurrentRequests(requestFn, maxConcurrent);
  }
  return limitedFetchInstance;
};
